/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.upf.grupoe.p2ppicture.DBAccessEngine.implementations;

/**
 *
 * @author Marc
 */
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class PhotoHandler extends org.xml.sax.helpers.DefaultHandler {
	
    private Photo photo;
    private StringBuffer accumulator;
    public static Log logger=LogFactory.getLog("Main");
        
    
    public PhotoHandler () {
	photo = new Photo();
    }

    public PhotoHandler (Photo ph) {
	photo = ph;
    }
    
    // Called at the beginning
    @Override
    public void startDocument() {
	accumulator = new StringBuffer();
    }

    // When the parser encounters plain text (not XML elements), it calls this method, which accumulates 
    // the text in a string buffer. Note that this method may be called in multiple times.
    @Override
    public void characters(char[] buffer, int start, int length) {
	accumulator.append(buffer, start, length);
    }

    // At the beginning of each new element, erase any accumulated text
    @Override
    public void startElement(String namespaceURL, String localName, String qname, Attributes attributes) {
	accumulator.setLength(0);
    }

    // Take special action when reach the end of selected elements. 
    // In this case the accumulated text is stored in the photo object
    @Override
    public void endElement(String namespaceURL, String localName, String qname)
    {
	if (localName.equals("keyword")) {        
		String keyword = accumulator.toString().trim();
		photo.addKeyword(keyword);
	}
	else if (localName.equals("id_picture")) {        
		photo.setId(accumulator.toString().trim());
	}
        else if (localName.equals("path")) {        
		photo.setPath(accumulator.toString().trim());
	}
    }

    // Called at the end
    public void endDocument() {
    }

    @Override
    public void warning(SAXParseException exception){   
        if(logger.isDebugEnabled()){    
            logger.info("WARNING: line " + exception.getLineNumber() + ": "+exception.getMessage());
        }
    }
    @Override
    public void error(SAXParseException exception) {
        if(logger.isDebugEnabled()){
            logger.error("ERROR: line " + exception.getLineNumber() + ": " +exception.getMessage());
        }
    }

    @Override
    public void fatalError(SAXParseException exception) throws SAXException {
        if(logger.isDebugEnabled()){	
            logger.error("FATAL: line " + exception.getLineNumber() + ": " + exception.getMessage());
        }
	throw(exception);
    }
}
